<template>
  <div class="dashboard">
    <!-- 标题 -->
<!--    <div class="title">-->
<!--      <h2></h2>-->
<!--      <div class="actions">-->
<!--        <el-button size="small">刷新</el-button>-->
<!--        <el-button size="small">返回</el-button>-->
<!--      </div>-->
<!--    </div>-->

    <!-- 今日数据卡片 -->
    <div class="data-cards" v-if="is_show_button('page_home_overview')">
      <el-row :gutter="20">
        <el-col :span="4" v-for="(item, index) in totalData" :key="index">
          <el-card shadow="always" class="data-card" :style="{ backgroundColor: item.color }">
            <h3>{{ item.value }}</h3>
            <p class="icon-text">{{ item.title }}</p>
          </el-card>
        </el-col>
      </el-row>
    </div>

<!--    自定义图标，以后改-->
<!--    <div class="section">-->
<!--      <h3>常用功能</h3>-->
<!--      <div class="icons">-->
<!--        <el-row :gutter="20">-->
<!--          <el-col :span="4" v-for="(icon, index) in sortedFunctions" :key="index">-->
<!--            <div class="icon-box" @click="navigateTo(icon.path)">-->
<!--              &lt;!&ndash; 使用图片代替el-icon &ndash;&gt;-->
<!--              <img :src="icon.image" alt="icon" class="icon-image" />-->
<!--              <p>{{ icon.label }}</p>-->
<!--            </div>-->
<!--          </el-col>-->
<!--        </el-row>-->
<!--      </div>-->
<!--    </div>-->

    <div class="section" v-if="is_show_button('page_home_common_functions') && judgeUserShow">
      <h3>常用功能</h3>
      <div class="icons">
        <el-row :gutter="90" class="icon-row">
          <el-col :span="3" v-for="(icon, index) in sortedFunctions" :key="index">
            <div class="icon-box" @click="navigateTo(icon.path)">
              <!-- 使用 Element UI 字体图标 -->
              <i :class="icon.iconClass" class="icon-font"></i>
              <p class="icon-text">{{ icon.label }}</p>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <div class="section" v-if="is_show_button('page_home_common_functions') && !judgeUserShow" >
      <h3>常用功能</h3>
      <div class="icons">
        <el-row :gutter="100" class="icon-row">
          <el-col :span="6" v-for="(icon, index) in sortedFunctionsCustomer" :key="index">
            <div class="icon-box" @click="navigateTo(icon.path)">
              <!-- 使用 Element UI 字体图标 -->
              <i :class="icon.iconClass" class="icon-font"></i>
              <p class="icon-text">{{ icon.label }}</p>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 需求总览 -->
    <div class="section" v-if="is_show_button('page_home_overview_data') && judgeUserShow">
      <el-row :gutter="20">
        <!-- 手表数据 -->
        <el-col :span="12">
          <el-card class="overview-card">
            <h3>需求总览（手表）</h3>
            <div class="overview-stats">
              <p class="icon-text">今日新增：<span class="highlight">{{ demandWatchData.today_count }}</span></p>
              <p class="icon-text">本月新增：<span class="highlight">{{ demandWatchData.month_count }}</span></p>
              <p class="icon-text">需求总数：<span class="highlight">{{ demandWatchData.total_count }}</span></p>
            </div>
          </el-card>
        </el-col>
        <!-- 电子烟数据 -->
        <el-col :span="12">
          <el-card class="overview-card">
            <h3>需求总览（电子烟）</h3>
            <div class="overview-stats">
              <p class="icon-text">今日新增：<span class="highlight">{{ demandVapeData.today_count }}</span></p>
              <p class="icon-text">本月新增：<span class="highlight">{{ demandVapeData.month_count }}</span></p>
              <p class="icon-text">需求总数：<span class="highlight">{{ demandVapeData.total_count }}</span></p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="section" v-if="is_show_button('page_home_overview_data') && judgeUserShow">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="overview-card">
            <h3>内置表盘总览</h3>
            <div class="overview-stats">
              <p class="icon-text">待上架：<span class="highlight">{{ builtInWatchData.total_test}}</span></p>
              <p class="icon-text">已上架：<span class="highlight">{{ builtInWatchData.total_pass }}</span></p>
              <p class="icon-text">全部表盘：<span class="highlight">{{ builtInWatchData.total_count }}</span></p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="overview-card">
            <h3>内置壁纸总览</h3>
            <div class="overview-stats">
              <p class="icon-text">待上架：<span class="highlight">{{ builtInWallpaperData.total_test}}</span></p>
              <p class="icon-text">已上架：<span class="highlight">{{ builtInWallpaperData.total_pass }}</span></p>
              <p class="icon-text">全部壁纸：<span class="highlight">{{ builtInWallpaperData.total_count }}</span></p>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <div class="chart-section" v-if="is_show_button('page_home_demand_statistics') && judgeUserShow">
      <h3>客户需求统计（新增）</h3>
      <div class="filters">
        <el-button-group>
          <el-button @click="fetchData('week', false)">本周</el-button>
          <el-button @click="fetchData('month', false)">本月</el-button>
        </el-button-group>
        <el-date-picker v-model="dateRange" type="daterange" placeholder="请选择日期范围" @change="handleDateRangeChange"></el-date-picker>
      </div>
      <div id="line-chart" class="chart"></div>
    </div>

    <div class="chart-section">
      <h3>客户需求趋势</h3>
      <div class="filters">
        <el-button-group>
          <el-button @click="fetchData('week', true)">本周</el-button>
          <el-button @click="fetchData('month', true)">本月</el-button>
          <el-button @click="fetchData('all', true)">总计</el-button>
        </el-button-group>
        <el-select v-model="currentFilter" placeholder="请选择分类" @change="updateChart1">
          <el-option label="按分辨率（手表）" value="resolution_watch"></el-option>
          <el-option label="按主控平台-型号（手表）" value="platform_watch"></el-option>
          <el-option label="按分辨率（电子烟）" value="resolution_vape"></el-option>
          <el-option label="按主控平台-型号（电子烟）" value="platform_vape"></el-option>
        </el-select>
      </div>
      <div id="bar-chart" class="chart"></div>

    </div>

    <el-dialog title="修改密码" :visible.sync="changePasswordShow" width="40%" center @close="closeDialog">
      <el-form :model="form" :rules="rules" ref="dialogForm">
        <el-form-item label="新密码：" :label-width="formLabelWidth" prop="newPassword">
          <el-input v-model="form.newPassword" autocomplete="off" placeholder="请输入新密码"
                    style="width: 100%;"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码：" :label-width="formLabelWidth" prop="againPassword">
          <el-input v-model="form.againPassword" autocomplete="off" placeholder="再次确认新密码"
                    style="width: 100%;"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button class="bt-color-tjd" type="primary" @click="modifyPassword">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>
import * as echarts from 'echarts/core'
import dayjs from 'dayjs'
import { post } from '@/api/my_axios'
import { delCookie } from '@/utils/aqi'

export default {
  data () {
    return {
      judgeUserShow: false,
      userInfo: {},
      totalData: [ // 统计总数默认值
        { title: '今日新增需求', value: '0', color: '#409EFF' },
        // { title: '今日转换需求', value: '0', color: '#FFC107' },
        { title: '今日完成需求', value: '0', color: '#409EFF' },
        { title: '已延期需求', value: '0', color: '#FFC107' },
        { title: '总计完成需求', value: '0', color: '#FF5722' },
        { title: '总计需求', value: '0', color: 'rgba(20,235,217,0.99)' }
      ],
      // overviewData: [], // 统计总览数据
      demandWatchData: { today_count: 0, month_count: 0, total_count: 0 }, // 统计总览数据-需求手表
      demandVapeData: { today_count: 0, month_count: 0, total_count: 0 }, // 统计总览数据-需求电子烟
      builtInWatchData: { total_test: 0, total_pass: 0, total_count: 0 }, // 统计总览数据-内置手表
      builtInWallpaperData: { total_test: 0, total_pass: 0, total_count: 0 }, // 统计总览数据-内置电子烟
      dateData: [], // 统计日期数据
      configurationData: [], // 统计配置数据
      builtInData: [], // 统计内置数据
      createBy: '',
      // icon字体
      functions: [
        { label: '添加表盘', iconClass: 'el-icon-plus', order: 1, path: '/BuiltInDial' },
        { label: '需求列表', iconClass: 'el-icon-document', order: 2, path: '/DemandSys' },
        { label: '客户管理', iconClass: 'el-icon-user', order: 3, path: '/CustomerManagement' },
        { label: '添加壁纸', iconClass: 'el-icon-plus', order: 4, path: '/BuiltInWallpaper' },
        { label: '添加基本配置', iconClass: 'el-icon-setting', order: 5, path: '/MaterielBasicConfiguration' },
        { label: '公告管理', iconClass: 'el-icon-bell', order: 6, path: '/NoticeColumn' },
        { label: '员工管理', iconClass: 'el-icon-star-on', order: 7, path: '/UserManagement' }
      ],
      // icon字体
      functionsCustomer: [
        { label: '添加需求', iconClass: 'el-icon-plus', order: 1, path: '/DemandCustomer' },
        { label: '需求列表', iconClass: 'el-icon-document', order: 2, path: '/DemandCustomer' },
        { label: '修改密码', iconClass: 'el-icon-setting', order: 2, path: '修改密码' },
        { label: '公告列表', iconClass: 'el-icon-bell', order: 6, path: '/NoticeMessageCustomer' }
      ],
      // 250114自定义图标以后用到再改
      // functions: [
      //   { label: '添加表单', image: require('@/assets/login/logo.png'), order: 1, path: '/add-form' },
      //   { label: '需求列表', image: 'path/to/document.png', order: 2, path: '/demand-list' },
      //   { label: '客户管理', image: 'path/to/user.png', order: 3, path: '/customer-management' },
      //   { label: '添加壁纸', image: 'path/to/picture.png', order: 4, path: '/add-wallpaper' },
      //   { label: '添加基本配置', image: 'path/to/setting.png', order: 5, path: '/add-config' },
      //   { label: '公告管理', image: 'path/to/bell.png', order: 6, path: '/announcement-management' },
      //   { label: '员工管理', image: 'path/to/star.png', order: 7, path: '/employee-management' }
      // ]
      // 客户需求统计（新增）
      dateRange: [], // 日期范围选择
      chart: null, // ECharts 实例
      kindNames: { 1: '手表', 3: '电子烟' }, // kind 映射
      // 客户需求趋势
      currentFilter: 'resolution_watch', // 默认选择
      chartInstance: null, // ECharts 实例
      queryParams: {
        kind: '1',
        statisticsType: 1,
        startDate: '',
        endDate: '',
        createBy: ''
      },
      changePasswordShow: false, // 修改密码
      form: {
        userId: '',
        newPassword: '',
        againPassword: ''
      },
      formLabelWidth: '140px',
      rules: {
        newPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 32, message: '密码必须是6到32个字符之间的字母+数字+符号', trigger: 'blur' },
          {
            pattern: /^[a-zA-Z0-9!@#$%^&*()\-+]+$/,
            message: '密码仅支持数字、字母和特殊符号 (!@#$%^&*()-+)',
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) => {
              if (!/[A-Za-z]/.test(value)) {
                callback(new Error('密码必须包含字母'))
              } else if (!/[0-9]/.test(value)) {
                callback(new Error('密码必须包含数字'))
              } else if (!/[!@#$%^&*()\-+]/.test(value)) {
                callback(new Error('密码必须包含特殊符号 (!@#$%^&*()-+)'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        againPassword: [{ required: true, message: '必填项不能为空！', trigger: 'change' }]
      }
    }
  },

  mounted () {
    this.$store.dispatch('getUserData').then(res => {
      this.userInfo = res.data.user
      this.judgeUserShow = this.userInfo.userType !== '02'
      this.initChart1() // 簇状图
      this.getStatisticalTotal()
      this.getStatisticalConfigurationData() // 默认加载数据
      if (this.judgeUserShow) {
        // 内部客户才能查询
        this.$nextTick(() => {
          this.initChart() // 折线图 等待 DOM 渲染后初始化图表
        })
        this.getStatisticalOverviewData()
        this.getStatisticalBuiltInData()
        this.fetchData('month', false) // 默认加载本月数据
      }
    })
  },

  computed: {
    // 按 order 排序
    sortedFunctions () {
      return this.functions.sort((a, b) => a.order - b.order)
    },
    // 按 order 排序
    sortedFunctionsCustomer () {
      return this.functionsCustomer.sort((a, b) => a.order - b.order)
    }
  },

  methods: {

    getStatisticalTotal () {
      if (!this.judgeUserShow) {
        this.createBy = this.$store.state.module1.UserInfo.userName
      }
      this.$store.dispatch('getStatisticalTotal', { createBy: this.createBy }).then(res => {
        // 假设接口返回的数据是 res.data
        if (res.code === 200) {
          // 更新 totalData 根据接口返回的数据
          const data = res.data
          this.totalData = [
            { title: '今日新增需求', value: data.today_added, color: '#57d7e6' },
            { title: '今日完成需求', value: data.today_completed, color: '#f8c838' },
            { title: '已延期需求', value: data.total_delayed, color: '#529ff1' },
            { title: '总计完成需求', value: data.total_completed, color: '#FF5722' },
            { title: '总计需求', value: data.total_demand, color: 'rgba(130,238,228,0.99)' }
          ]
        }
      }).catch(error => {
        console.error('获取数据失败:', error)
      })
    },

    getStatisticalOverviewData () {
      this.$store.dispatch('getStatisticalOverviewData', { createBy: this.createBy }).then(res => {
        // 假设接口返回的数据是 res.data
        if (res.code === 200) {
          res.data.forEach(item => {
            if (item.kind === '1') {
              // 手表
              this.demandWatchData = item
            } else if (item.kind === '3') {
              // 电子烟
              this.demandVapeData = item
            }
          })
        }
      }).catch(error => {
        console.error('获取数据失败:', error)
      })
    },

    getStatisticalBuiltInData () {
      this.$store.dispatch('getStatisticalBuiltInData', { createBy: this.createBy }).then(res => {
        // 假设接口返回的数据是 res.data
        if (res.code === 200) {
          res.data.forEach(item => {
            if (item.kind === '1') {
              // 手表
              this.builtInWatchData = item
            } else if (item.kind === '3') {
              // 电子烟
              this.builtInWallpaperData = item
            }
          })
        }
      }).catch(error => {
        console.error('获取数据失败:', error)
      })
    },

    getStatisticalDateData (startDate, endDate) {
      this.$store.dispatch('getStatisticalDateData', { startDate, endDate }).then(res => {
        if (res.code === 200) {
          this.processData(res.data, startDate, endDate)
        }
      }).catch(error => {
        console.error('获取数据失败:', error)
      })
    },

    getStatisticalConfigurationData () {
      this.queryParams.kind = this.currentFilter.includes('watch') ? '1' : '3'
      this.queryParams.statisticsType = this.currentFilter.includes('resolution') ? 1 : 2
      if (!this.judgeUserShow) {
        this.queryParams.createBy = this.$store.state.module1.UserInfo.userName
      }
      this.$store.dispatch('getStatisticalConfigurationData', {
        statisticsType: this.queryParams.statisticsType,
        kind: this.queryParams.kind,
        startDate: this.queryParams.startDate,
        endDate: this.queryParams.endDate,
        createBy: this.queryParams.createBy
      }).then(res => {
        // 假设接口返回的数据是 res.data
        if (res.code === 200) {
          this.updateChartData1(res.data)
        }
      }).catch(error => {
        console.error('获取数据失败:', error)
      })
    },

    // 新增折线图-用户选择日期范围时触发
    handleDateRangeChange (value) {
      if (value && value.length === 2) {
        const [startDate, endDate] = value
        this.getStatisticalDateData(startDate, endDate)
      }
    },

    // 新增折线图-初始化图表
    initChart () {
      this.chart = echarts.init(document.getElementById('line-chart'))
      this.chart.setOption({
        title: { text: '' },
        tooltip: { trigger: 'axis' },
        legend: { data: Object.values(this.kindNames) },
        xAxis: { type: 'category', boundaryGap: false, data: [] },
        yAxis: { type: 'value' },
        series: []
      })
    },

    // 新增折线图-处理接口数据并补全
    processData (data, startDate, endDate) {
      const days = this.generateDateRange(startDate, endDate)
      const seriesData = {}

      // 初始化 seriesData，根据 kind 分组
      Object.keys(this.kindNames).forEach((kind) => {
        seriesData[kind] = days.map((day) => ({ day, count: 0 }))
      })

      // 填充数据
      data.forEach((item) => {
        const { kind, day, count } = item
        const target = seriesData[kind]?.find((d) => d.day === day)
        if (target) target.count = parseInt(count, 10)
      })

      // 更新图表
      this.updateChart(days, seriesData)
    },

    // 新增折线图-生成日期范围数组
    generateDateRange (startDate, endDate) {
      const start = dayjs(startDate)
      const end = dayjs(endDate)
      const range = []
      for (let date = start; date.isBefore(end) || date.isSame(end, 'day'); date = date.add(1, 'day')) {
        range.push(date.format('YYYY-MM-DD'))
      }
      return range
    },

    // 新增折线图-更新 ECharts 图表
    updateChart (days, seriesData) {
      if (this.chart) { // 确保 this.chart 已初始化
        const series = Object.keys(this.kindNames).map((kind) => ({
          name: this.kindNames[kind],
          type: 'line',
          data: seriesData[kind].map((item) => item.count)
        }))
        this.chart.setOption({
          xAxis: { data: days },
          series
        })
      } else {
        console.error('Chart is not initialized yet.')
      }
    },

    // 优化后的fetchData函数,日期选择
    fetchData (type, isFetchData1 = false) {
      // 根据时间类型设置查询范围
      const today = dayjs()
      let startDate, endDate

      // 计算日期范围
      if (type === 'week') {
        startDate = today.startOf('week').format('YYYY-MM-DD')
        endDate = today.endOf('week').format('YYYY-MM-DD')
      } else if (type === 'month') {
        startDate = today.startOf('month').format('YYYY-MM-DD')
        endDate = today.endOf('month').format('YYYY-MM-DD')
      }
      // 根据参数判断调用哪个接口
      if (isFetchData1) {
        // 如果是 fetchData1 的调用方式，更新 queryParams 并调用 getStatisticalConfigurationData
        this.queryParams.startDate = startDate
        this.queryParams.endDate = endDate
        this.getStatisticalConfigurationData()
      } else {
        // 默认调用 getStatisticalDateData
        this.getStatisticalDateData(startDate, endDate)
      }
    },

    // 配置簇状图-初始化
    initChart1 () {
      this.chartInstance = echarts.init(document.getElementById('bar-chart'))
    },

    updateChart1 (filterType) {
      // 更新查询条件
      if (filterType) {
        this.currentFilter = filterType
      }
      this.getStatisticalConfigurationData()
    },

    updateChartData1 (data) {
      // const allCategories = ['240'] // 预设分类
      // const categoryMap = Object.fromEntries(data.map((item) => [item.xAxis, item.count]))
      //
      // const categories = allCategories
      // const values = categories.map((cat) => parseInt(categoryMap[cat] || 0, 10))

      // 处理接口返回数据
      const categories = data.map((item) => item.xAxis)
      const values = data.map((item) => parseInt(item.count, 10))

      const option = {
        title: { text: '' },
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: categories
        },
        yAxis: { type: 'value' },
        series: values.length > 0 ? [{
          type: 'bar',
          data: values,
          itemStyle: { color: '#7fbbf9' }
        }] : [],
        graphic: values.length === 0 ? [
          {
            type: 'text',
            left: 'center',
            top: 'middle',
            style: {
              text: '暂无数据',
              fontSize: 20,
              fill: '#ccc'
            }
          }
        ] : []
      }
      this.chartInstance.setOption(option)
    },

    modifyPassword () {
      if (this.form.newPassword !== this.form.againPassword) {
        this.$message.error('两次密码不一样！')
        return
      }
      post('/api/crm/sys/manage/crm/user/resetUserPwd',
        { password: this.form.newPassword, userId: this.form.userId }).then(req => {
        if (req && req.code === 200) {
          this.$message({ message: '修改成功！', type: 'success' })
          this.closeDialog()
          this.$router.push('/Login')
          delCookie('token')
        }
      })
    },

    // 关闭dialog框
    closeDialog () {
      this.$refs.dialogForm.resetFields()
      this.changePasswordShow = false
      Object.keys(this.form).forEach(key => {
        this.form[key] = ''
      })
    },

    // 接口跳转
    navigateTo (path) {
      if (path === '修改密码') {
        this.changePasswordShow = true
        this.form.userId = this.userInfo.userId
      } else {
        this.$router.push(path)
      }
    },

    is_show_button (name) {
      // let show = false
      // this.$store.state.module1.menu_list.forEach(v => {
      //   // eslint-disable-next-line eqeqeq
      //   if (v.path === name) {
      //     show = true
      //   }
      // })
      // return show
      return true
    }

  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
  height: calc(100vh - 40px); /* 自动适应屏幕 */
  overflow-y: auto; /* 启用垂直滚动条 */
  box-sizing: border-box;
}
.title {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.data-cards {
  margin: 20px 0;
}
.data-card {
  text-align: center;
  color: #fff;
}
.section {
  margin: 20px 0;
  text-align: center;
}

.icons {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  flex-wrap: wrap; /* 当空间不足时换行 */
}

.icon-box {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px 15px; /* 控制间距 */
  flex: 1 1 auto; /* 自动调整大小 */
}

.icon-box:hover {
  transform: scale(1.1);
}

.icon-font {
  font-size: 40px; /* 调大图标大小 */
  color: #333;
  margin-bottom: 8px; /* 图标和文字间距 */
}

.icon-text {
  font-size: 18px; /* 调大文字大小 */
  color: #555;
  white-space: nowrap; /* 禁止文字换行 */
  text-align: center;
}
.icon {
  display: block;
  margin: 0 auto 10px;
}
.overview-card {
  padding: 20px;
}
.overview-stats {
  line-height: 1.8;
}
.highlight {
  font-size: 18px;
  font-weight: bold;
  color: red;
}
.chart-section {
  margin-top: 20px;
  text-align: center;
}
.filters {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.chart {
  height: 400px;
}

.icon-box:hover {
  transform: scale(1.1);
}

.icon-image {
  width: 50px;
  height: 50px;
  margin-bottom: 10px;
}

p {
  margin: 0;
  font-size: 14px;
  color: #333;
}
</style>
